package com.suyx.job.config;


import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.suyx.job.core.IHoldService;

import lombok.extern.slf4j.Slf4j;

/**
 * @Description:
 * @author: suyx
 * @date: 2019年9月2019/9/28日 17:47
 */

@Configuration
@Slf4j
public class InitCoreConfig {
    @Bean
    public IHoldService getLocalHoldService(){
    	log.info("正在配置InitCoreConfig");
        return new IHoldService() {
            @Override
            public <T> T getServiceInstance(Class<T> t) throws Exception{
                return Optional.ofNullable(SpringContextUtils.getBean(t))
                        .orElseThrow(()->new Exception("unFoundService",new Throwable("未找到%s类的实例对象")));
            }

            @SuppressWarnings("unchecked")
			@Override
            public <T> T getServiceInstance(String serviceName) throws Exception {
                return (T)Optional.ofNullable(SpringContextUtils.getBean(serviceName))
                        .orElseThrow(()->new Exception("unFoundService",new Throwable("未找到实例名为[%s]的实例对象")));
            }

            @Override
            public <T> List<T> getServiceInstances(Class<T> clazz) throws Exception{
                return Optional.ofNullable(SpringContextUtils.getBeans(clazz).stream().collect(Collectors.toList()))
                        .orElseThrow(()->new Exception("unfFoundServices",new Throwable("未找到%s类的实例对象集合")));
            }
        };
    }
}
